package com.repair.controller;

import com.repair.entity.ForumPost;
import com.repair.entity.ForumComment;
import com.repair.entity.User;
import com.repair.service.ForumService;
import com.repair.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/forum")
public class ForumController {

    @Autowired
    private ForumService forumService;

    @Autowired
    private UserService userService;

    @PostMapping("/posts")
    public ResponseEntity<?> createPost(@RequestBody ForumPost post,
                                      @AuthenticationPrincipal UserDetails userDetails) {
        User user = userService.getByUsername(userDetails.getUsername());
        post.setUserId(user.getId());
        post.setUserType(user.getRole());
        forumService.createPost(post);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/posts")
    public ResponseEntity<Map<String, Object>> getPostList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        List<ForumPost> posts = forumService.getPostList(page, size);
        int total = forumService.getPostCount();
        return ResponseEntity.ok(Map.of(
            "posts", posts,
            "total", total
        ));
    }

    @PostMapping("/comments")
    public ResponseEntity<?> createComment(@RequestBody ForumComment comment,
                                         @AuthenticationPrincipal UserDetails userDetails) {
        User user = userService.getByUsername(userDetails.getUsername());
        comment.setUserId(user.getId());
        comment.setUserType(user.getRole());
        forumService.createComment(comment);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/posts/{postId}/comments")
    public ResponseEntity<List<ForumComment>> getCommentList(@PathVariable Long postId) {
        return ResponseEntity.ok(forumService.getCommentList(postId));
    }

    @GetMapping("/comments/{parentId}/replies")
    public ResponseEntity<List<ForumComment>> getReplyList(@PathVariable Long parentId) {
        return ResponseEntity.ok(forumService.getReplyList(parentId));
    }

    @DeleteMapping("/posts/{postId}")
    public ResponseEntity<?> deletePost(@PathVariable Long postId) {
        forumService.deletePost(postId);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/comments/{commentId}")
    public ResponseEntity<?> deleteComment(@PathVariable Long commentId) {
        forumService.deleteComment(commentId);
        return ResponseEntity.ok().build();
    }
} 